"use client";

import { useState } from "react";
import { Button, Card, App } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import { useRouter } from "next/navigation";
import { api } from "~/trpc/react";
import { type Course } from "@prisma/client";
import { CourseForm } from "./CourseForm";
import { CourseCard } from "./CourseCard";
import { Pagination } from "../common/Pagination";

export function CourseList() {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [editingCourse, setEditingCourse] = useState<Course | null>(null);
  const { message, modal } = App.useApp();
  const router = useRouter();

  const { data, isLoading, refetch } = api.courses.list.useQuery({
    page: currentPage,
    pageSize,
  });

  const deleteMutation = api.courses.delete.useMutation({
    onSuccess: async () => {
      message.success("课程删除成功");
      await refetch();
    },
    onError: (error) => {
      message.error(error.message || "删除失败，请重试");
    },
  });

  const handleDelete = async (course: Course) => {
    try {
      const confirmed = await modal.confirm({
        title: "确认删除",
        content: "确定要删除这个课程吗？此操作不可恢复。",
        okText: "确认",
        cancelText: "取消",
        okButtonProps: {
          danger: true,
        },
      });

      if (confirmed) {
        await deleteMutation.mutateAsync(course.id);
      }
    } catch (error) {
      if (error instanceof Error) {
        console.error("删除课程时出错:", error);
      }
    }
  };

  const handleModalClose = () => {
    setIsModalOpen(false);
    setEditingCourse(null);
  };

  return (
    <div>
      <div className="mb-4 flex justify-between items-center">
        <h1 className="text-2xl font-bold">课程列表</h1>
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={() => setIsModalOpen(true)}
        >
          新建课程
        </Button>
      </div>
      
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {data?.items.map(course => (
          <CourseCard
            key={course.id}
            course={course}
            onDelete={handleDelete}
          />
        ))}
      </div>

      <Pagination
        current={currentPage}
        pageSize={pageSize}
        total={data?.total}
        onChange={(page, size) => {
          setCurrentPage(page);
          setPageSize(size);
        }}
        showSizeChanger
        showTotal={(total) => `共 ${total} 条`}
      />

      {!data?.items.length && !isLoading && (
        <div className="text-center py-8 text-gray-500">
          还没有课程，点击右上角添加新课程
        </div>
      )}

      <CourseForm
        open={isModalOpen}
        initialValues={editingCourse || undefined}
        onCancel={handleModalClose}
        onSuccess={async () => {
          handleModalClose();
          await refetch();
        }}
      />
    </div>
  );
} 